package com.cirkana.viewer.share;

import java.io.DataInputStream;
import java.io.DataOutputStream;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.cirkana.CirkanaException;
import com.cirkana.PassData;
import com.cirkana.ViewerActivity;
import com.cirkana.serial.bin.BinarySerializationException;
import com.cirkana.serial.bin.BinarySerializationUtil;
import com.cirkana.viewer.R;
import com.cirkana.viewer.data.security.User;

public class ShareActivity extends ViewerActivity {

	// private static String requestToken =
	// "284095635-A60nkEBwax1EWdsECFaANIqaCVI19KzUQGfWRPS9";
	// private static String requestSecret =
	// "I1RC8kR1WYvMEiLrO0A0ThFqf0j2lWyZvDRFy2NNac";
	// private static String twitterUser = "bernatfabregat";

	private EditText messageEditText = null;
	private Button sendButton = null;

	private SharePassData data;
	private IShareServiceProxy serviceProxy;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);

		this.messageEditText = (EditText) findViewById(R.id.share_message);
		this.sendButton = (Button) findViewById(R.id.share_send);
		this.data = (SharePassData) getRequest(SharePassData.class);

		try {
			this.serviceProxy = ServiceController.getShareServiceProxy(this.data.getServiceName());

//			this.data.getUser().setUserServices(new UserServicesList());
//			UserService userService = new UserService();
//			userService.setNickName("bernatfabregat");
//			userService.setSecurityData(new String[] { "284095635-A60nkEBwax1EWdsECFaANIqaCVI19KzUQGfWRPS9", "I1RC8kR1WYvMEiLrO0A0ThFqf0j2lWyZvDRFy2NNac" });
//			this.data.getUser().getUserServices().put(IShareServiceProxy.SHARE_SERVICE_TWITTER, userService);

			this.serviceProxy.setUser(this.data.getUser());
			if (!this.serviceProxy.hasAccess())
				resolveShareServiceAccess();
			else
				prepareAccess();
		} catch (Exception e) {
			showErrorMessage(e);
		}
	}

	protected void prepareAccess() throws ShareServiceException {
		this.serviceProxy.prepareAccess();
		this.sendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					sendMessage();
				} catch (Exception e) {
					showErrorMessage(e);
				}
			}
		});

	}

	protected void resolveShareServiceAccess() throws CirkanaException {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.sharecredentials);
		dialog.setTitle(getLiteral(R.string.share));
		dialog.getWindow().setLayout(getWindowManager().getDefaultDisplay().getWidth() - 15, getWindowManager().getDefaultDisplay().getHeight() - 30);

		final Button okButton = (Button) dialog.findViewById(R.id.sharecredentials_ok);
		final EditText userEditText = (EditText) dialog.findViewById(R.id.sharecredentials_user);
		final EditText passwordEditText = (EditText) dialog.findViewById(R.id.sharecredentials_password);

		okButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					String serviceUser = userEditText.getText().toString();
					String servicePassword = passwordEditText.getText().toString();
					dialog.dismiss();
					String[] securityData = serviceProxy.resolveAccess(serviceUser, servicePassword);					
				} catch (ShareServiceException e) {
					showErrorMessage(e);
				}
			}
		});

		dialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface arg0) {
			}
		});

		dialog.show();
	}

	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// super.onActivityResult(requestCode, resultCode, data);
	//
	// switch (requestCode) {
	// case REQUEST_AUTHORINGTWITTER:
	// switch (resultCode) {
	// case AuthoringTwitterActivity.RESULT_AUTHORINGTWITTER_OK:
	// try {
	// AuthoringTwitterPassData result = (AuthoringTwitterPassData) getResponse(
	// data, AuthoringTwitterPassData.class);
	// oauthClient.setAuthorizationCode(result.getPin());
	// String[] accessToken = oauthClient.getAccessToken();
	// requestToken = accessToken[0];
	// requestSecret = accessToken[1];
	// sendTwitterMessage();
	// } catch (SerializationException e) {
	// showErrorMessage(e);
	// }
	// break;
	// }
	// break;
	// }
	//
	// }

	protected void sendMessage() throws BinarySerializationException, ShareServiceException {
		this.serviceProxy.sendMessage(this.messageEditText.getText().toString());
		setResponse(RESULT_OK, data);
		finish();
	}

	public static class SharePassData extends PassData {

		private String serviceName;
		private User user;

		public String getServiceName() {
			return serviceName;
		}

		public void setServiceName(String serviceName) {
			this.serviceName = serviceName;
		}

		public User getUser() {
			return user;
		}

		public void setUser(User user) {
			this.user = user;
		}

		public SharePassData() {
		}

		public SharePassData(String serviceName, User user) {
			this.serviceName = serviceName;
			this.user = user;
		}

		@Override
		public void serialize(DataOutputStream out) throws BinarySerializationException {
			BinarySerializationUtil.serializeString(this.serviceName, out);
			BinarySerializationUtil.serializeSerializable(this.user, out);
		}

		@Override
		public void deserialize(DataInputStream in) throws BinarySerializationException {
			this.serviceName = BinarySerializationUtil.deserializeString(in);
			this.user = (User) BinarySerializationUtil.deserializeSerializable(User.class, in);
		}

		@Override
		public String toString() {
			StringBuilder s = new StringBuilder("{");

			s.append("shareType=");
			if (this.serviceName == null)
				s.append("(null)");
			else
				s.append(this.serviceName);
			s.append(",user=");
			if (this.user == null)
				s.append("(null)");
			else
				s.append(this.user.toString());
			s.append("}");

			return s.toString();
		}
	}
}
